package com.codeoss.module.account.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.framework.service.impl.BaseService;
import com.codeoss.module.account.dao.AccountInvoiceLineMapper;
import com.codeoss.module.account.model.AccountInvoiceLine;
import com.codeoss.module.account.model.AccountTax;
import com.codeoss.module.account.service.IAccountInvoiceLineService;
import com.codeoss.module.account.service.IAccountTaxService;
import com.codeoss.module.uom.service.IUomUomConversionService;

@Service
public class AccountInvoiceLineService extends BaseService<AccountInvoiceLineMapper, AccountInvoiceLine>
		implements IAccountInvoiceLineService {
	@Autowired
    private IUomUomConversionService uomUomConversionService;
	@Autowired
	private IAccountTaxService accountTaxService;
	public void insert(AccountInvoiceLine accountInvoiceLine) {
		beforeSave(accountInvoiceLine,true);
		super.insert(accountInvoiceLine);
	}
	
	public void update(AccountInvoiceLine accountInvoiceLine) {
		beforeSave(accountInvoiceLine,false);
		super.update(accountInvoiceLine);
	}
	
	protected void beforeSave(AccountInvoiceLine accountInvoiceLine,boolean isNewRecord) {
		Long productId=accountInvoiceLine.getProductProductId();
	    BigDecimal qtyEntered=accountInvoiceLine.getQtyEntered();
	    BigDecimal priceEntered=accountInvoiceLine.getPriceEntered();
	    Long taxId=accountInvoiceLine.getAccountTaxId();
	    Long uomUomId=accountInvoiceLine.getUomUomId();
	    BigDecimal discount=accountInvoiceLine.getDiscount();
	    if(productId!=null&&qtyEntered!=null&& priceEntered!=null&&taxId!=null&&uomUomId!=null) {
	    	BigDecimal qtyInvoiced=uomUomConversionService.convert(productId, uomUomId, qtyEntered);
	    	accountInvoiceLine.setQtyInvoiced(qtyInvoiced);
	    	BigDecimal total=qtyInvoiced.multiply(priceEntered);
	    	if(discount!=null) {
				total=total.multiply(new BigDecimal(100).subtract(discount)).divide(new BigDecimal(100));
			}
	    	AccountTax accountTax=accountTaxService.getById(taxId);
			BigDecimal accountRate=(new BigDecimal(100)).add(accountTax.getRate()).divide(new BigDecimal(100));
	    	total=total.multiply(accountRate);
	    	accountInvoiceLine.setAmountSubtotal(total);
	    }else {
	    	accountInvoiceLine.setAmountSubtotal(null);
	    }
	}

	@Override
	public List<AccountInvoiceLine> getLineListByAccountInvoiceId(Long accountInvoiceId) {
		// TODO Auto-generated method stub
		QueryWrapper<AccountInvoiceLine> query=new QueryWrapper<AccountInvoiceLine>();
		query.eq("account_invoice_id", accountInvoiceId);
		return list(query);
	}
}